package com.atguigu.chapter11;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Csv;
import org.apache.flink.table.descriptors.Kafka;
import org.apache.flink.table.descriptors.Schema;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/6/19 9:26
 */
public class Flink04_Table_Connector_Sink_Kafka {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // 1. 创建一个流
        DataStreamSource<WaterSensor> stream = env.fromElements(
            new WaterSensor("sensor_1", 1000L, 10),
            new WaterSensor("sensor_1", 2000L, 20),
            new WaterSensor("sensor_2", 3000L, 30),
            new WaterSensor("sensor_1", 4000L, 40)
        );
        
        // 2. 创建流式表的环境
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        // 3. 把流转成动态表
        Table table = tEnv.fromDataStream(stream);
        
        Table t1 = table
            .where($("id").isEqual("sensor_1"))
            .select($("id"), $("vc"));
        
        // 把t1的数据写入到Kafka
        tEnv
            .connect(
                new Kafka()
                    .version("universal")
                    .property("bootstrap.servers", "hadoop162:9092")
                    .topic("s2")
                    .sinkPartitionerRoundRobin()
            )
//            .withFormat(new Json())
            .withFormat(new Csv().lineDelimiter(""))
            .withSchema(new Schema().field("id", DataTypes.STRING()).field("vc", DataTypes.INT()))
            .createTemporaryTable("s2");
    
        t1.executeInsert("s2");
    
        //env.execute();  // 如果没有对流的任何操作, 不需要执行
        
        
    }
}
